package qj.ac.support;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

import qj.ui.ImagePane;
import qj.util.DesktopUtil;
import qj.util.StringUtil;
import qj.util.SwingUtil;
import qj.util.SwingUtil.RowAdder;
import qj.util.ThreadUtil;
import qj.util.appCommon.swing.AppFrame;
import qj.util.math.Color;
import qj.util.math.Dimension;
import qj.util.math.Rectangle;
import qj.util.swing.ImgCond;
import qj.util.swing.MemImage;

public class ColorDetector {
	static int RATIO = 20;
	public static void main(String[] args) {
		ImagePane imagePane = new ImagePane(null);
		imagePane.setPreferredSize(new Dimension(5*RATIO ,5*RATIO).toAwt());

		JPanel panel = new JPanel();
		RowAdder ra = SwingUtil.rowAdder(panel);
		JTextField hexTf = new JTextField(20);
		JTextField totalTf = new JTextField(20);
		JTextField codeTf = new JTextField(20);
		
		ra.row("Hex", hexTf);
		ra.row("Total", totalTf);
		ra.row("Code", codeTf);
		
		AppFrame frame = new AppFrame("Color");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Container cp = frame.getContentPane();
		cp.setLayout(new BorderLayout());
		cp.add(imagePane,BorderLayout.WEST);
		cp.add(panel,BorderLayout.CENTER);
		frame.setAlwaysOnTop(true);
		frame.setVisible(true);
		
		while (true) {
			ThreadUtil.sleep(100);
			java.awt.Point p = MouseInfo.getPointerInfo().getLocation();
			MemImage memImage = new MemImage(DesktopUtil.capture(new Rectangle(p.x - 2, p.y - 2,5,5)));
			BufferedImage image = memImage.toImage(RATIO);
			Graphics2D g = image.createGraphics();
			g.setColor(Color.red.toAwt());
			g.drawRect(RATIO * 2 - 1, RATIO * 2 - 1, RATIO + 1, RATIO + 1);
			g.dispose();
			imagePane.setImage(image);
			
			Color color = memImage.getColor(2, 2);
			if (color!=null) {
				hexTf.setText("#" + StringUtil.toHex(color.getRed()) + StringUtil.toHex(color.getGreen()) + StringUtil.toHex(color.getBlue()));
				totalTf.setText("" + ImgCond.total(color));
				codeTf.setText("new Color(" + color.getRed() + ","
						+ color.getGreen() + "," + color.getBlue() + ")");
			}
		}
	}
}
